<template>
  <div class="p-2">
    <transition>
      <div v-show="showSearch" class="search">
        <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="68px">
          <el-form-item label="销售日期">
            <div style="display: flex">
              <el-date-picker
                v-model="dateRangeSaleTime.beginSaleTime"
                style="width: 150px"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="date"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0)]"
                placeholder="开始日期"
              />
              <div style="margin: 0 5px">-</div>
              <el-date-picker
                v-model="dateRangeSaleTime.endSaleTime"
                style="width: 150px"
                :default-time="[new Date(2000, 1, 1, 23, 59, 59)]"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="date"
                placeholder="结束日期"
              />
            </div>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['crm:saleReport:add']" type="primary" plain icon="Plus" @click="handleAdd">新增 </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['crm:saleReport:edit']" type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
              >修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['crm:saleReport:remove']" type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
              >删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['crm:saleReport:export']" type="warning" plain icon="Download" @click="handleExport">导出 </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="saleReportList" show-summary @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="40" align="center" />
        <el-table-column label="销售日期" align="center" prop="saleTime" width="100">
          <template #default="scope">
            <span>{{ dayjs(scope.row.saleTime).format('YYYY-MM-DD') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备用金" align="center" prop="spareMoney" />
        <el-table-column label="销售收入" align="center" prop="saleMoney" min-width="90px" />
        <el-table-column label="其他收入" align="center" prop="otherMoney" />
        <el-table-column label="货款支出" align="center" prop="goodsMoney" />
        <el-table-column label="代付款" align="center" prop="agentMoney" min-width="90px" />
        <el-table-column label="其他支出" align="center" prop="otherExpenditure" />
        <el-table-column label="银行存款" align="center" prop="bankMoney" min-width="90px" />
        <el-table-column label="开支" align="center" prop="expenditure" />
        <el-table-column label="理论结余" align="center" prop="balance" min-width="90px" />
        <el-table-column label="实收现金" align="center" prop="money" />
        <el-table-column label="毛利率" align="center" prop="grossProfitMargin" />
        <el-table-column label="销售利润" align="center" prop="saleProfit" />
        <el-table-column label="毛利润" align="center" prop="grossProfit" />
        <el-table-column label="结算差异" align="center" prop="difference">
          <template #default="scope">
            <span v-if="scope.row.difference < 0" style="color: red">{{ scope.row.difference }}</span>
            <span v-else>{{ scope.row.difference }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button v-hasPermi="['crm:saleReport:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button v-hasPermi="['crm:saleReport:remove']" link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>
    <!-- 添加或修改销售日报对话框 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="700px"
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form ref="saleReportFormRef" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="销售日期" prop="saleTime" style="width: 278px">
              <el-date-picker v-model="form.saleTime" clearable type="date" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择销售日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备用金" prop="spareMoney">
              <el-input v-model="form.spareMoney" placeholder="请输入备用金" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="销售收入" prop="saleMoney">
              <el-input v-model="form.saleMoney" placeholder="请输入销售收入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="其他收入" prop="otherMoney">
              <el-input v-model="form.otherMoney" placeholder="请输入其他收入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="货款支出" prop="goodsMoney">
              <el-input v-model="form.goodsMoney" placeholder="请输入货款支出" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="代付款" prop="agentMoeny">
              <el-input v-model="form.agentMoney" placeholder="请输入代付款" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="换购支出" prop="otherExpenditure">
              <el-input v-model="form.otherExpenditure" placeholder="请输入其他支出" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="银行存款" prop="bankMoney">
              <el-input v-model="form.bankMoney" placeholder="请输入银行存款" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开支" prop="expenditure">
              <el-input v-model="form.expenditure" placeholder="请输入支出" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="实收现金" prop="money">
              <el-input v-model="form.money" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="毛利率" prop="grossProfitMargin">
              <el-input v-model="form.grossProfitMargin" style="width: 200px">
                <template #suffix>
                  <span>%</span>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="理论结余" prop="balance">
              <el-input v-model="form.balance" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="销售利润" prop="saleProfit">
              <el-input v-model="form.saleProfit" placeholder="请输入销售利润" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="毛利润" prop="grossProfit">
              <el-input v-model="form.grossProfit" placeholder="请输入毛利润" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结算差异" prop="difference">
              <el-input v-model="form.difference" placeholder="请输入结算差异" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="SaleReport" lang="ts">
import { addSaleReport, delSaleReport, getSaleReport, listSaleReport, updateSaleReport } from '@/api/crm/saleReport';
import { SaleReportForm, SaleReportQuery, SaleReportVO } from '@/api/crm/saleReport/types';
import dayjs from 'dayjs';
import modal from '@/plugins/modal';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const saleReportList = ref<SaleReportVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const dateRangeSaleTime = ref<any>({
  beginSaleTime: '',
  endSaleTime: ''
});
const queryFormRef = ref<ElFormInstance>();
const saleReportFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: SaleReportForm = {
  id: undefined,
  saleTime: undefined,
  spareMoney: undefined,
  saleMoney: undefined,
  otherMoney: 0,
  goodsMoney: 0,
  agentMoney: 0,
  otherExpenditure: 0,
  bankMoney: 0,
  expenditure: 0,
  balance: undefined,
  money: 0,
  grossProfitMargin: 20,
  saleProfit: undefined,
  grossProfit: undefined,
  difference: undefined
};
const data = reactive<PageData<SaleReportForm, SaleReportQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    saleMoney: undefined,
    otherMoney: undefined,
    goodsMoney: undefined,
    agentMoney: undefined,
    otherExpenditure: undefined,
    bankMoney: undefined,
    expenditure: undefined,
    saleProfit: undefined,
    grossProfit: undefined,
    difference: undefined,
    params: {
      saleTime: '111'
    }
  },
  rules: {
    id: [{ required: true, message: 'ID不能为空', trigger: 'blur' }],
    saleTime: [{ required: true, message: '销售日期不能为空', trigger: 'blur' }],
    spareMoney: [{ required: true, message: '备用金不能为空', trigger: 'blur' }],
    saleMoney: [{ required: true, message: '销售收入不能为空', trigger: 'blur' }],
    bankMoney: [{ required: true, message: '银行存款不能为空', trigger: 'blur' }],
    saleProfit: [{ required: true, message: '销售利润不能为空', trigger: 'blur' }],
    money: [{ required: true, message: '实收现金不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

watch(()=>[data.form.money,data.form.grossProfitMargin],()=>{
  let diff =
    Number(data.form.spareMoney) +
    Number(data.form.saleMoney) +
    Number(data.form.otherMoney) -
    Number(data.form.goodsMoney) -
    Number(data.form.otherExpenditure) -
    Number(data.form.bankMoney) -
    Number(data.form.expenditure) -
    Number(data.form.money);
  data.form.difference = Number(-diff.toFixed(2));
  //理论结余=销售收入+其他收入-货款支出-代付货款-其他支出-银行存款-开支
  let bal =
    Number(data.form.saleMoney) +
    Number(data.form.otherMoney) -
    Number(data.form.goodsMoney) -
    Number(data.form.agentMoney) -
    Number(data.form.otherExpenditure) -
    Number(data.form.bankMoney) -
    Number(data.form.expenditure);
  data.form.balance = Number(bal.toFixed(2));
  //销售利润=销售额*毛利率
  let sal = Number(data.form.saleMoney) * (Number(data.form.grossProfitMargin) / 100);
  data.form.saleProfit = Number(sal.toFixed(2));
  //毛利润=其他收入+销售利润
  let gross = Number(data.form.saleProfit) + Number(data.form.otherMoney);
  data.form.grossProfit = Number(gross.toFixed(2));

})

/** 查询销售日报列表 */
const getList = async () => {
  loading.value = true;
  queryParams.value.params = { ...dateRangeSaleTime.value };
  const res: any = await listSaleReport(queryParams.value);
  saleReportList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  saleReportFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  // dateRangeSaleTime.value = ['', ''];
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: SaleReportVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加销售日报';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: SaleReportVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getSaleReport(_id);
  console.log(res);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改销售日报';
};

/** 提交按钮 */
const submitForm = () => {
  saleReportFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateSaleReport(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addSaleReport(form.value).finally(() => (buttonLoading.value = false));
      }
      modal.msgSuccess('修改成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: SaleReportVO) => {
  const _ids = row?.id || ids.value;
  await modal.confirm('是否确认删除销售日报编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delSaleReport(_ids);
  modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'crm/saleReport/export',
    {
      ...queryParams.value
    },
    `saleReport_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getList();
});
</script>
